package cn.edu.dlut.ssdut.foodCredit2012.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import cn.edu.dlut.ssdut.foodCredit2012.model.BasicCollection;
import cn.edu.dlut.ssdut.foodCredit2012.util.HibernateUtil;

public class BasicCollectionService {
	
	public void add(BasicCollection b) throws Exception{
		if(!hasBasic(b)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(b);
			session.getTransaction().commit();
		}
	}
	
	public void delete(BasicCollection b) throws Exception{
		if(hasBasic(b)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.delete(b);
			session.getTransaction().commit();
		}
	}
	
	public void update (BasicCollection b) throws Exception{
		if(hasBasic(b)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.update(b);
			session.getTransaction().commit();
		}
	}
	
	public List<BasicCollection> basicCList() {
		List<BasicCollection> basicCList;
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from BasicCollection");
		query.setFirstResult(1);
		query.setMaxResults(10);
		basicCList = query.list();
		
		session.getTransaction().commit();
		
		return basicCList;
	}
	
	public boolean hasBasic(BasicCollection b) throws Exception {
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		long count = (Long)session.createQuery("select count(*) from BasicCollection b where b.licenceID = :licenceID")
			.setString("licenceID", b.getLicenceID())
			.uniqueResult();
		session.getTransaction().commit();
		
		if(count > 0) return true;
		return false;
		
	}
	
	public BasicCollection load(BasicCollection b) throws Exception{
		if(hasBasic(b)){
			b = loadByLicenceID(b.getLicenceID());
			return b;
		}
		return b;
	}
	
	public BasicCollection loadByLicenceID(String licenceID){
		BasicCollection b = new BasicCollection();
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		b = (BasicCollection)session.createQuery("select b from BasicCollection b where b.licenceID = :licenceID")
			.setParameter("licenceID", licenceID)
			.uniqueResult();
		
		session.getTransaction().commit();
		
		return b;
	}

}
